package com.surprise.biz.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

import com.google.common.collect.Lists;
import com.surprise.redis.LuaLoader;
import com.surprise.redis.RedisFactory;
import com.surprise.redis.RedisKeyGenerator;

/**
 * IdGenerator.java
 * @author nick
 * @since 2015年5月5日
 */
@Component
public class IdGenerator {	
	@Autowired
	private RedisFactory redisFactory;
	@Autowired
	private LuaLoader luaLoader;
	
	public static final String LUA_NAME = "keygen";
	
	/**
     * redis中值为当前最大id
     * +1并返回当前值，就是最大id
     * @param s
     * @return
     */
    public Long genId(String s) {        
        Jedis jedis = null;
        try {
            jedis = redisFactory.getClient();
            return genId(jedis, s);
        } finally {
            redisFactory.returnResource(jedis);
        }
    }
    
    /**
     * redis中值为当前最大id
     * +1并返回当前值，就是最大id
     * @param jedis
     * @param s
     * @return
     */
    public Long genId(Jedis jedis, String s) {
        String key = RedisKeyGenerator.commonKvIdgenerator(s);
        String id = (String)jedis.eval(luaLoader.getLua(LUA_NAME), Lists.newArrayList(key), Lists.newArrayList("1"));
        return id == null ? 0L : Long.valueOf(id);
    }
    
    /**
     * redis中值为当前最大id
     * +num并返回当前值，就是最大id
     * @param s
     * @param num
     * @return
     */
    public List<Long> genId(String s, int num) {        
        Jedis jedis = null;        
        try {
            jedis = redisFactory.getClient();
            return genId(jedis, s, num);
        } finally {
            redisFactory.returnResource(jedis);
        }
    }
    
    /**
     * redis中值为当前最大id
     * +num并返回当前值，就是最大id
     * @param jedis
     * @param s
     * @param num
     * @return
     */
    public List<Long> genId(Jedis jedis, String s, int num) {
        List<Long> ids = Lists.newArrayList();
        String key = RedisKeyGenerator.commonKvIdgenerator(s);
        String idStr = (String)jedis.eval(luaLoader.getLua(LUA_NAME), Lists.newArrayList(key), Lists.newArrayList(""+num));
        Long id = Long.valueOf(idStr);
        for(int i=num-1;i>=0;i--) {
            ids.add(id-i);
        }
        return ids;
    }
    
    public static enum TYPE {
    	COMMENT("comment"),
    	SPOT("spot");
    	public String name;
    	private TYPE(String name) {
    		this.name = name;
    	}
    }
}
